package chapter19;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/24 21:58
 */
public class MaterWorkerDemo2 {
    public static void main(String[] args) throws InterruptedException {
        final int num = 100;
        CountDownLatch latch = new CountDownLatch(num);
        Thread[] workers = new Thread[num];
        for (int i = 0; i < num; i++) {
            workers[i] = new Thread(new Worker2(latch));
            workers[i].start();
        }
        latch.await();
        System.out.println("collecting result from works");
    }

    static class Worker2 implements Runnable {
        private CountDownLatch latch;

        public Worker2(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            int sleep = (int) (Math.random() * 1000);
            System.out.println(Thread.currentThread().getName() + " sleep for " + sleep + " ms");

            try {
                if (sleep < 200) {
                    throw new RuntimeException("bad luck");
                }
                TimeUnit.MILLISECONDS.sleep(sleep);
            } catch (InterruptedException e) {
            } finally {
                this.latch.countDown();
            }
        }
    }
}
